﻿using Batman.Cms.Core.Core.Configurations;
using Batman.Cms.Core.Models.UpYun;
using System;
using System.Threading.Tasks;

namespace Batman.Cms.Core.Tools
{
    public class UpYunTool
    {
        public UpYunConfigurations UpYunConfigurations;

        public UpYunTool(UpYunConfigurations upYunConfigurations)
        {
            UpYunConfigurations = upYunConfigurations;
        }

        public async Task<UpYunUploadResult> UploadSync(byte[] data)
        {
            var upYunConfiguration = UpYunConfigurations.Default;

            var client = new UpYun.NETCore.UpYunClient(upYunConfiguration.Bucketname, upYunConfiguration.Account, upYunConfiguration.Password);

            var path = DefinedPath("jpg");

            var success = await client.WriteFileAsync(path, data, true);

            return new UpYunUploadResult(success, $"{upYunConfiguration.Domain}{path}");
        }

        private string DefinedPath(string fileExtension)
        {
            var now = DateTime.Now;
            var filename = Guid.NewGuid().ToString();
            var extension = fileExtension.TrimStart('.');
            return $"/{now.Year.ToString()}/{now.ToString("MMdd")}/{filename}.{extension}";
        }
    }
}
